import axios from "axios";
import { assignUndefinedValue } from "../common";
import { formatTime, getNowFormatDate } from "../time";
/* 查询数据 */
export const getAllUser = () => {
    return axios.get('/user')
}
export const getAllChildren = () => {
    return axios.get(`/children`)
}
export const getAllDepartment = () => {
    return axios.get('/department')
}
export const getAllHeader = () => {
    return axios.get('/header')
}
export const getAllRole = () => {
    return axios.get('/role')
}
export const getAllRight = () => {
    return axios.get('/right')
}
export const getAllRoleRight = () => {
    return axios.get('/role_right')
}
export const getAllCategory = () => {
    return axios.get('/category')
}
export const getAllService = () => {
    return axios.get('/service')
}
export const getAllChannel = () => {
    return axios.get('/channel')
}
export const getAllLocation = () => {
    return axios.get('/location')
}
export const getAllAuditState = () => {
    return axios.get('/audit')
}
export const getAllRecord = () => {
    return axios.get('/record')
}
export const getAllCustomer = () => {
    return axios.get('/customer')
}
export const getAllBank = () => {
    return axios.get('/bank')
}
export const getAllCategoryService = () => {
    return axios.get(`/category_service`)
}
export const getAllRisk = () => {
    return axios.get(`/risk`)
}
export const getAllType = () => {
    return axios.get('/type')
}
export const getAllCirculation = () => {
    return axios.get('/circulation')
}



export const getUserById = (userId) => {
    return axios.get(`/user/${userId}`)
}
export const getRightById = (rightId) => {
    return axios.get(`/right/${rightId}`)
}
export const getChildrenByRightId = (rightId) => {
    return axios.get(`/children?rightId=${rightId}`)
}
export const getRightsByRoleId = (roleId) => {
    return axios.get(`/role_right?roleId=${roleId}`)
}
export const getRecordsByUserId = (userId) => {
    return axios.get(`/record?userId=${userId}`)
}
export const getCategoryServiceById = (categoryId, serviceId) => {
    return axios.get(`/category_service?categoryId=${categoryId}&serviceId=${serviceId}`)
}
export const getServicesByCategoryId = (categoryId) => {
    return axios.get(`/category_service?categoryId=${categoryId}`)
}
export const getBankRecordById = (bankId) => {
    return axios.get(`/bank/${bankId}`)
}
export const getUsernameById = async (userId) => {
    const res = await axios.get(`/user/${userId}`);
    if (res.status === 200) {
        return res.data.user.username;
    } else {
        return false;
    }
}


export const getUserByName = (username) => {
    return axios.get(`/user?username=${username}`)
}

export const getLoginUserByName = (username) => {
    return axios.get(`/login?username=${username}`)
}

export const getLoginUserById = (userId) => {
    return axios.get(`/login?userId=${userId}`)
}


export const getRightIdBykey = (key) => {
    return axios.get(`/right?key=${key}`)
}


// 返回页面所需数据
export const getChildrenArray = (rights, childrens, rightId) => {
    let res = []
    res.push(...childrens.filter(x => x.rightId === rightId))
    for (let i = 0; i < res.length; i++) {
        const item = res[i];
        for (let j = rightId; j < rights.length; j++) {
            const r = rights[j];
            if (item.key === r.Right.key) {
                item.id = r.Right.id
                break
            }
        }
    }
    return res
}

/* 结果格式 [{id, key, title, pagePermission, grade, children:[]}] */
export const getRights = (roleId) => {
    return axios.all([getRightsByRoleId(roleId), getAllChildren()])
        .then(axios.spread((res1, res2) => {
            const { rights } = res1.data
            const { childrens } = res2.data
            // console.log(rights);
            if (rights) {
                let result = []
                for (let i = 0; i < rights.length; i++) {
                    const item = rights[i];
                    const { key, title, id, pagePermission, grade } = item.Right
                    const children = getChildrenArray(rights, childrens, id)
                    result.push({ id, key, title, pagePermission, grade, children })
                }
                return result
            }
        }))
}

/* 返回right的key数组 */
export const getRightsArray = (role_rights, allRight, roleId) => {
    let res = []
    // 从role_rights数组中筛选出相同roleId的元素
    res.push(...role_rights.filter(x => x.roleId === roleId))
    let result = []
    for (let i = 0; i < res.length; i++) {
        const item = res[i];
        for (let j = 0; j < allRight.length; j++) {
            const r = allRight[j];
            if (item.rightId === r.id) {
                result.push(r.key)
                break
            }
        }
    }
    return result
}

/* 结果格式 [{id, roleName, rights:[]}] */
export const getRoles = () => {
    return axios.all([getAllRole(), getAllRoleRight(), getAllRight()])
        .then(axios.spread((res1, res2, res3) => {
            const { roles } = res1.data
            const { role_rights } = res2.data
            const allRight = res3.data.rights
            if (roles) {
                let result = []
                for (let i = 0; i < roles.length; i++) {
                    const item = roles[i];
                    const { id, roleName } = item
                    const rights = getRightsArray(role_rights, allRight, id)
                    result.push({ id, roleName, rights })
                }
                return result
            }
        }))
}

export const getRightKeyByRightId = async (rightId) => {
    const res = await axios.get(`/right/${rightId}`)
    if (res.status === 200) {
        return res.data.right.key
    } else {
        return false
    }

}

// 获取新增角色的权限信息
export const getRightsOfNewRole = async (rightId) => {
    if (typeof rightId === 'string') {
        rightId = parseInt(rightId)
    }
    const rightRes = await getChildrenByRightId(rightId)
    const data = rightRes.data.childrens
    let keys = []
    if (data.length === 0) {
        const key = await getRightKeyByRightId(rightId)
        if (key) {
            keys.push(key)
            return { allRightId: [], keys }
        }
    }

    let result = []
    result.push(rightId)
    keys.push(data[0].Right.key)
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.rightId === rightId) {
            keys.push(item.key)
            const rightResByKey = await getRightIdBykey(item.key)
            const right = rightResByKey.data.right
            if (right) {
                result.push(right.id)
            } else {
                return [rightResByKey.data.msg]
            }
        }
    }
    // console.log(result);
    // console.log(keys);
    return {
        allRightId: result, keys
    }
}
const getRecords = async (token) => {
    const { userId, roleId } = token
    let res = null;
    if (roleId === 1) {
        res = await getRecordsByUserId(userId);
    } else {
        res = await getAllRecord();
    }
    const records = res.data.records;
    return records;
};

const parseRecord = async (record) => {
    const { Category, Customer, Service, Channel, Location, Audit, Bank, User } = record;
    const result = await getCategoryServiceById(Category.id, Service.id);
    const { Circulation, Type, Risk, timeLimit } = result.data.category_service;
    const bankRes = await getBankRecordById(Bank.id);
    const bankRecord = bankRes.data.bank;

    const categoryName = Category.title;
    const serviceName = Service.title;
    const customerName = Customer.name;
    const bankName = bankRecord.name;
    const username = User.username;
    const channel = Channel.title;
    const location = Location.title;
    const auditState = Audit.title;
    const circulation = Circulation.title;
    const type = Type.title;
    const risk = Risk.title;

    const obj = {
        ...Customer,
        ...bankRecord,
        categoryName,
        serviceName,
        bankName,
        customerName,
        channel,
        location,
        auditState,
        circulation,
        type,
        risk,
        timeLimit,
        username,
        ...record,
    };

    return obj;
};

export const getServiceListInformation = async (token) => {
    const records = await getRecords(token);

    if (records.length === 0) {
        return { list: [], Records: {} };
    }

    const parsedRecords = await Promise.all(records.map(parseRecord));

    const { categories, services, customers, risks,
        banks, channels, locations, auditStates, headers } = await getSerivceInformation()
    const Bank = banks.map(item => ({ id: item.id, title: item.name }))
    const Customer = customers.map(item => ({ id: item.id, title: item.identityId }))
    // 存储记录用于更新时获取id信息
    const Records = {
        categories, services, risks, channels, locations, headers,
        customers: Customer,
        banks: Bank, auditStates,
    }

    // console.log(Records);
    // let res = []
    // for (let i = parsedRecords.length - 1; i >= 0; i--) {
    //     const element = parsedRecords[i];
    //     console.log(element.createdAt);
    //     res.push(element);
    // }

    return {
        list: parsedRecords, Records
    }
}

export const patchAuditInformation = async (records) => {
    // console.log(records);
    if (records.length === 0) return null
    return await Promise.all(records.map(async (record) => {
        const { auditUserId, Customer, Category, Service, Audit } = record;
        const userRes = auditUserId ? await getUsernameById(auditUserId) : null;

        const categoryName = Category.title
        const serviceName = Service.title;
        const customerName = assignUndefinedValue(Customer.name);
        const auditUsername = userRes ? userRes : '';
        const auditState = Audit.title

        return {
            customerName,
            auditUsername,
            ...Customer,
            ...record,
            categoryName,
            serviceName,
            auditState
        };
    }));
}

export const getAuditListInformation = async (token) => {
    const [recordsRes, auditRes, headerRes, categoryRes, serviceRes] = await Promise.all([
        getAllRecord(),
        getAllAuditState(),
        getAllHeader(),
        getAllCategory(),
        getAllService()
    ]);

    let records = recordsRes.data.records;
    const audits = auditRes.data.auditStates;
    const categories = categoryRes.data.categories;
    const services = serviceRes.data.services;

    const header = headerRes.data.headers[0];

    if (!records || records.length === 0) {
        return [];
    }
    if (token.roleId !== 5) {
        records = records.filter(record => record.User.id === token.userId)
    }

    const list = await patchAuditInformation(records)

    return {
        list, audits, header, categories, services
    }
}

export const getHomeInformation = async (token) => {
    const recordRes = await getAllRecord()
    let records = recordRes.data.records
    let _timeLimit = []
    let _risk = []
    let _category = []
    let _emergent = []
    const today = getNowFormatDate()
    // console.log(today);
    if (token.roleId !== 5) {
        records = records.filter(record => record.User.id === token.userId)
    }

    for (let i = 0; i < records?.length; i++) {
        const item = records[i];
        // console.log(item);
        // console.log(formatTime(item.endTime));
        if (formatTime(item.endTime) <= today && item.auditId !== 3) {
            // console.log(222);
            _emergent.push(item);
        }
        const category_serviceRes = await getCategoryServiceById(item.categoryId, item.serviceId)
        // console.log(category_serviceRes.data.category_service);
        const { timeLimit, Risk: { title, id } } = category_serviceRes.data.category_service
        // 统计不同办理时限的业务数量
        let isFind = false
        for (let j = 0; j < _timeLimit.length; j++) {
            const element = _timeLimit[j];
            if (element.title === timeLimit) {
                const id = element.id
                _timeLimit = _timeLimit.filter(item => item.title !== timeLimit)
                _timeLimit.push({ id, title: timeLimit, num: element.num + 1 })
                isFind = true
                break
            }
        }
        if (!isFind) {
            _timeLimit.push({ id: i, title: timeLimit, num: 1 })
        }

        // 统计不同风险等级的业务数量
        isFind = false
        for (let j = 0; j < _risk.length; j++) {
            const element = _risk[j];
            if (element.title === title) {
                const id = element.id
                _risk = _risk.filter(item => item.title !== title)
                _risk.push({ id, title: title, num: element.num + 1 })
                isFind = true
                break
            }
        }
        if (!isFind) {
            _risk.push({ id, title: title, num: 1 })
        }

        // 统计不同种类的业务数量
        isFind = false
        const { Category, categoryId } = item
        const categoryName = Category?.title
        for (let j = 0; j < _category.length; j++) {
            const element = _category[j];
            if (element.title === categoryName) {
                const id = element.id
                _category = _category.filter(item => item.title !== categoryName)
                _category.push({ id, title: categoryName, num: element.num + 1 })
                isFind = true
                break
            }
        }
        if (!isFind) {
            _category.push({ id: categoryId, title: categoryName, num: 1 })
        }
    }
    return {
        timeLimit: _timeLimit,
        risk: _risk,
        emergent: _emergent,
        categories: _category
    }
}

export const getSerivceInformation = () => {
    return axios.all([
        getAllCategory(), getAllService(), getAllChannel(),
        getAllLocation(), getAllAuditState(), getAllHeader(),
        getAllCustomer(), getAllBank(), getAllRisk()
    ]).then(axios.spread((res1, res2, res3, res4, res5, res6, res7, res8, res9) => {
        const { categories } = res1.data
        const { services } = res2.data
        const { channels } = res3.data
        const { locations } = res4.data
        const { auditStates } = res5.data
        const { headers } = res6.data
        const { customers } = res7.data
        const { banks } = res8.data
        const { risks } = res9.data
        return {
            categories, services, channels, locations, auditStates, headers, customers, banks, risks
        }
    }))
}

export const getPersonalServiceData = async (userId) => {
    const recordRes = await getRecordsByUserId(userId)
    const records = recordRes.data.records
    let _categories = []
    let _audits = []
    for (let i = 0; i < records?.length; i++) {
        const item = records[i];
        // console.log(item);
        const { Category: { title, id }, Audit } = item

        // 统计不同种类的业务数量
        let isFind = false
        for (let j = 0; j < _categories.length; j++) {
            const element = _categories[j];
            if (element.title === title) {
                const id = element.id
                _categories = _categories.filter(x => x.title !== title)
                _categories.push({ id, title, num: element.num + 1 })
                isFind = true
                break
            }
        }
        if (!isFind) {
            _categories.push({ id, title, num: 1 })
        }

        // 统计不同审核类型的业务数量
        const auditState = Audit.title
        isFind = false
        for (let j = 0; j < _audits.length; j++) {
            const element = _audits[j];
            if (element.title === auditState) {
                const id = element.id
                _audits = _audits.filter(x => x.title !== auditState)
                _audits.push({ id, title: auditState, num: element.num + 1 })
                isFind = true
                break
            }
        }
        if (!isFind) {
            _audits.push({ id: Audit.id, title: auditState, num: 1 })
        }
        // console.log(_categories);
        // console.log(_audits);
    }
    return {
        categories: _categories,
        auditStates: _audits
    }
}


export const getAllCategoryServiceInformation = async () => {
    const [cate_serviceRes, categoryRes, serviceRes, headerRes] = await Promise.all([
        getAllCategoryService(),
        getAllCategory(),
        getAllService(),
        getAllHeader()
    ]);
    const categories = categoryRes.data.categories
    const services = serviceRes.data.services
    const headers = headerRes.data.headers

    const data = cate_serviceRes.data.category_services
    if (data.length === 0) return null
    const list = await Promise.all(data.map(async (item) => {
        const { Bank, Circulation, Category, Service, Risk, Type } = item;

        const categoryName = Category.title
        const serviceName = Service.title;
        const circulation = Circulation.title;
        const risk = Risk.title;
        const type = Type.title;

        return {
            circulation,
            risk,
            ...Bank,
            ...item,
            categoryName,
            serviceName,
            type
        };
    }));
    return { list, categories, services, headers }
}

export const getEventInformation = async () => {
    const [circulationRes, typeRes, riskRes] = await Promise.all([
        getAllCirculation(),
        getAllType(),
        getAllRisk()
    ]);
    const circulations = circulationRes.data.circulations
    const types = typeRes.data.types
    const risks = riskRes.data.risks

    return { circulations, types, risks }
}


